/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.ipo.mm.web.actions;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.apache.struts.actions.DispatchAction;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.util.MessageResources;
import org.ipo.mm.ejb.entities.Actions;
import org.ipo.mm.ejb.entities.City;
import org.ipo.mm.ejb.entities.Institution;
import org.ipo.mm.ejb.entities.InstitutionFamily;
import org.ipo.mm.ejb.entities.InstitutionRegion;
import org.ipo.mm.ejb.entities.InstitutionType;
import org.ipo.mm.ejb.entities.Meeting;
import org.ipo.mm.ejb.entities.Representative;
import org.ipo.mm.ejb.entities.User;
import org.ipo.mm.ejb.facade.document.DocumentFacadeLocal;
import org.ipo.mm.ejb.facade.actions.ActionsFacadeLocal;
import org.ipo.mm.ejb.facade.city.CityFacadeLocal;
import org.ipo.mm.ejb.facade.family.InstitutionFamilyFacadeLocal;
import org.ipo.mm.ejb.facade.institution.InstitutionFacadeLocal;
import org.ipo.mm.ejb.facade.log.LogFacadeLocal;
import org.ipo.mm.ejb.facade.meeting.MeetingFacadeLocal;
import org.ipo.mm.ejb.facade.region.InstitutionRegionFacadeLocal;
import org.ipo.mm.ejb.facade.representative.RepresentativeFacadeLocal;
import org.ipo.mm.ejb.facade.type.InstitutionTypeFacadeLocal;


import org.ipo.mm.ejb.facade.user.UserFacadeLocal;
import org.ipo.mm.web.formbeans.CityBean;
import org.ipo.mm.web.formbeans.InstitutionBean;
import org.ipo.mm.web.formbeans.MeetingBean;
import org.ipo.mm.web.formbeans.RepresentativeBean;
import org.ipo.mm.web.util.BreadCrumbs;
import org.ipo.mm.web.util.ConstantManager;

import java.sql.Connection;
import java.sql.DriverManager;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.jasperreports.engine.JasperRunManager;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Properties;
import org.apache.struts.Globals;
import org.ipo.mm.ejb.entities.Document;

/**
 *
 * @author makcro
 */
public class DispatcherAction extends DispatchAction {

    /**
     * This is the Struts action method called on
     * http://.../actionPath?method=myAction1,
     * where "method" is the value specified in <action> element : 
     * ( <action parameter="method" .../> )
     */
    public ActionForward showMainPage(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        pushBreadCrumb("Main page", request);



        ActionForward actionForward = mapping.findForward(ConstantManager.NAVIGATION_MAINPAGE);
        return actionForward;
    }

    public ActionForward displayReport(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        try {
            Properties envProps = System.getProperties();
            Logger.getLogger(getClass().getName()).log(Level.INFO, "__________________________ BEGIN JAVA SETTINGS _______________________________");
            //System.out.println("__________________________ BEGIN JAVA SETTINGS _______________________________");
            for (Enumeration e = envProps.propertyNames(); e.hasMoreElements();) {
                String prop = (String) e.nextElement();
                Logger.getLogger(getClass().getName()).log(Level.INFO, prop + " : " + envProps.getProperty(prop));
                //System.out.println(prop + " : " + envProps.getProperty(prop));
            }
            //System.out.println("_____________________________END JAVA SETTINGS _______________________________");
            Logger.getLogger(getClass().getName()).log(Level.INFO, "_____________________________END JAVA SETTINGS _______________________________");


            Logger.getLogger(getClass().getName()).log(Level.INFO, "Begin");

            ServletOutputStream servletOutputStream = response.getOutputStream();
            Logger.getLogger(getClass().getName()).log(Level.INFO, "servletOutputStream");
            InputStream reportStream = getServlet().getServletConfig().getServletContext().getResourceAsStream("/WEB-INF/reports/CityReport.jasper");

            if (reportStream.available() > 0) {
                Logger.getLogger(getClass().getName()).log(Level.INFO, "našo report");
            }
            response.setContentType("application/pdf");
            response.addHeader("Content-Disposition", "attachment; filename=report.pdf");
            Class.forName("com.mysql.jdbc.Driver");
            Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/ipo?user=app_server&password=123456");
            Logger.getLogger(getClass().getName()).log(Level.INFO, "prije JasperRunManager ");
            JasperRunManager.runReportToPdfStream(reportStream, servletOutputStream, new HashMap(), connection);
            Logger.getLogger(getClass().getName()).log(Level.INFO, "nakon JasperRunManager ");


            servletOutputStream.flush();
            servletOutputStream.close();
            Logger.getLogger(getClass().getName()).log(Level.INFO, "flush close");

        } catch (Exception e) {
            Logger.getLogger(getClass().getName()).log(Level.INFO, "123Exception{0}", e.toString());

        } finally {
            return mapping.getInputForward();
        }
        /*
        try {
        Logger.getLogger(getClass().getName()).log(Level.INFO, "Begin");

        ServletOutputStream servletOutputStream = response.getOutputStream();
        Logger.getLogger(getClass().getName()).log(Level.INFO, "servletOutputStream");

        InputStream reportStream = getServlet().getServletConfig().getServletContext().getResourceAsStream("/WEB-INF/reports/CityReport.jasper");

        if(reportStream.available()>0) {
        Logger.getLogger(getClass().getName()).log(Level.INFO, "našo report");
        }
        response.setContentType("application/pdf");
        Class.forName("com.mysql.jdbc.Driver");
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/ipo?user=app_server&password=123456");

        Logger.getLogger(getClass().getName()).log(Level.INFO, "prije JasperRunManager ");
        //byte[] bytes =null;
        
        JasperRunManager.runReportToPdfStream(reportStream,servletOutputStream, new HashMap(), connection);
        Logger.getLogger(getClass().getName()).log(Level.INFO, "nakon JasperRunManager ");

        servletOutputStream.flush();
        servletOutputStream.close();
        Logger.getLogger(getClass().getName()).log(Level.INFO, "flush close");

        } catch(Exception e) {
        Logger.getLogger(getClass().getName()).log(Level.INFO, "123Exception{0}", e.toString());

        } finally {
        return mapping.getInputForward();
        }
         */
        /*ServletOutputStream servletOutputStream = null;

        servletOutputStream = response.getOutputStream();

        File reportFile = new File(getServletConfig().getServletContext().getRealPath("/WEB-INF/FirstReport.jasper"));

        byte[] bytes = null;

        try {
        bytes = JasperRunManager.runReportToPdf(reportFile.getPath(),
        new HashMap(), new JREmptyDataSource());

        response.setContentType("application/pdf");
        response.setContentLength(bytes.length);

        servletOutputStream.write(bytes, 0, bytes.length);
        servletOutputStream.flush();
        servletOutputStream.close();

        } catch (Exception e) {
        StringWriter stringWriter = new StringWriter();
        PrintWriter printWriter = new PrintWriter(stringWriter);
        e.printStackTrace(printWriter);
        }*/

        /*
        Connection connection;
        ServletOutputStream servletOutputStream =response.getOutputStream();
        InputStream reportStream = getServlet().getServletConfig().getServletContext().getResourceAsStream("/reports/CityReport.jasper");
        response.setContentType("application/pdf");
        Class.forName("com.mysql.jdbc.Driver");
        connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/ipo?user=app_server&password=123456");
        JasperRunManager.runReportToPdfStream(reportStream,servletOutputStream, new HashMap(), connection);
        connection.close();
        servletOutputStream.flush();
        servletOutputStream.close();
        return mapping.getInputForward();
         */


    }

    public ActionForward showReportsMenu(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        List<InstitutionRegion> allRegions = lookupInstitutionRegionFacade().findAll();
        request.setAttribute("allRegions", allRegions);
        List<InstitutionFamily> allFamilies = lookupInstitutionFamilyFacade().findAll();
        request.setAttribute("allFamilies", allFamilies);
        List<InstitutionType> allTypes = lookupInstitutionTypeFacade().findAll();
        request.setAttribute("allTypes", allTypes);
        List<Institution> allInst = lookupInstitutionFacade().findAll();
        request.setAttribute("allInst", allInst);

        //request.getSession().setAttribute("allRegions", allRegions);
        ActionForward actionForward = mapping.findForward(ConstantManager.NAVIGATION_REPORT_MENU);
        return actionForward;
    }

    public ActionForward showPrintPostMail(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        ActionForward forward = null;

        pushBreadCrumb(ConstantManager.BC_PRINT_BULK_POST_MAIL, request);


        List<Representative> allReps = lookupRepresentativeFacade().findAll();

        List<Representative> justOnesWithPostAddress = new Vector<Representative>();

        for (Iterator<Representative> it = allReps.iterator(); it.hasNext();) {
            Representative representative = it.next();
            if (representative.getInstitution() != null) {
                if (representative.getInstitution().getCity() != null) {
                    if (representative.getInstitution().getAddress().isEmpty() == false
                            && representative.getInstitution().getCity().getName().isEmpty() == false) {
                        justOnesWithPostAddress.add(representative);
                    }
                }
            }


        }

        request.getSession().setAttribute(ConstantManager.SESSION_REPRESENTATIVES, justOnesWithPostAddress);

        forward = mapping.findForward(ConstantManager.NAVIGATION_PRINT_BULK_MAIL_LIST);

        return forward;

    }

    public ActionForward showPrintPostMailInst(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        ActionForward forward = null;
        List<Institution> allInst = lookupInstitutionFacade().findAll();
        request.setAttribute("allInst", allInst);
        forward = mapping.findForward(ConstantManager.NAVIGATION_PRINT_BULK_MAIL_LIST_INST);
        return forward;
    }

    public ActionForward showSendMail(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        ActionForward forward = null;
        pushBreadCrumb(ConstantManager.BC_SEND_BULK_MAIL, request);
        List<Representative> allReps = lookupRepresentativeFacade().findWithEmail();
        request.getSession().setAttribute(ConstantManager.SESSION_REPRESENTATIVES, allReps);
        forward = mapping.findForward(ConstantManager.NAVIGATION_SEND_BULK_MAIL_LIST);
        return forward;
    }

        public ActionForward showSendMailInstitution(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
            ActionForward forward = null;
            List<Institution> allInst = lookupInstitutionFacade().findWithEmail();
            request.setAttribute("allInst", allInst);
            //forward = mapping.findForward(ConstantManager.NAVIGATION_PRINT_BULK_MAIL_LIST_INST);
            forward = mapping.findForward(ConstantManager.NAVIGATION_SEND_BULK_MAIL_LIST_INST);

            return forward;
    }

    public ActionForward showCreateCityForm(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        pushBreadCrumb(ConstantManager.BC_CITY_CREATE, request);
        ActionForward actionForward = null;
        //load all regions and store it in session
        List<InstitutionRegion> regions = lookupInstitutionRegionFacade().findAll();
        //Logger.getLogger(getClass().getName()+" method showCreateCityForm").log(Level.INFO, "getting regions");
        //Logger.getLogger(getClass().getName()+" method showCreateCityForm").log(Level.INFO, "size of list: {0}", String.valueOf(regions.size()));

        request.setAttribute("dispatch.CityForm.regions", regions);
        //Logger.getLogger(getClass().getName()+" method showCreateCityForm").log(Level.INFO, "regions put in session ");
        CityBean cBean = (CityBean) request.getSession().getAttribute("CityBean");
        //Logger.getLogger(getClass().getName()+" method showCreateCityForm").log(Level.INFO, "City name from session={0}",cBean.getName());

        if (cBean != null) {
            //Logger.getLogger(getClass().getName()+" method showCreateCityForm").log(Level.INFO, "RESET CITY BEAN");

            cBean.reset(mapping, request);
        }
        actionForward = mapping.findForward(ConstantManager.NAVIGATION_CITY_FORM);
        return actionForward;
    }

    public ActionForward showUpdateCityForm(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

       // pushBreadCrumb("Update city", request);
        //load all inst. regions and store it in session
        List<InstitutionRegion> regions = lookupInstitutionRegionFacade().findAll();
        request.setAttribute("dispatch.CityForm.regions", regions);
        String cityIdS = request.getParameter("cid");
        User user = (User) request.getSession().getAttribute(ConstantManager.SESSION_USER_PARAM_NAME);
        Integer cityId = Integer.valueOf(cityIdS);
        City city = lookupCityFacade().find(cityId);
        request.getSession().setAttribute("updateCity.city", city);
        ActionForward actionForward = mapping.findForward(ConstantManager.NAVIGATION_CITY_FORM);
        return actionForward;
    }
 public ActionForward viewCityForm(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        pushBreadCrumb("Update city", request);
        //load all inst. regions and store it in session
        List<InstitutionRegion> regions = lookupInstitutionRegionFacade().findAll();
        request.setAttribute("dispatch.CityForm.regions", regions);
        String cityIdS = request.getParameter("cid");
        User user = (User) request.getSession().getAttribute(ConstantManager.SESSION_USER_PARAM_NAME);
        Integer cityId = Integer.valueOf(cityIdS);
        City city = lookupCityFacade().find(cityId);
        request.getSession().setAttribute("updateCity.city", city);
        ActionForward actionForward = mapping.findForward(ConstantManager.NAVIGATION_CITY_FORM);
        return actionForward;
    }



   


    public ActionForward deleteCity(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {


        String cityIdS = request.getParameter("cid");
        User user = (User) request.getSession().getAttribute(ConstantManager.SESSION_USER_PARAM_NAME);

        Integer cityId = Integer.valueOf(cityIdS);
        City city = lookupCityFacade().find(cityId);
        city.setDeleted(true);
        lookupCityFacade().edit(city);

        //log
        lookupLogFacade().logDelete(user, ConstantManager.CITY_NAME, city.getName());
        notifyOperatoinStatus(ConstantManager.OPERATION_TYPE_DELETE, ConstantManager.CITY_ENTITY_NAME_RES_KEY, city.getName(), request);

        BreadCrumbs bc = (BreadCrumbs) request.getSession().getAttribute(ConstantManager.SESSION_BREADCRUMB_PARAM_NAME);

        ActionForward actionForward = bc.pop().getActionForward();
        return actionForward;
    }

    public ActionForward showCities(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        //load all inst. regions and store it in session
        //List<InstitutionRegion> regions = lookupInstitutionRegionFacade().findAll();
        //request.getSession().setAttribute("dispatch.showCreateInstForm.regions", regions);

        pushBreadCrumb("All cities", request);

        List<City> allCities = lookupCityFacade().findAll();
        request.setAttribute("showCities.cities", allCities);

        ActionForward actionForward = mapping.findForward(ConstantManager.NAVIGATION_CITY_LIST);
        return actionForward;
    }

    public ActionForward showCreateTypeForm(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        pushBreadCrumb("Create type", request);

        ActionForward actionForward = mapping.findForward(ConstantManager.NAVIGATION_TYPE_FORM);
        return actionForward;
    }

    public ActionForward showUpdateTypeForm(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        pushBreadCrumb("Update type", request);
        User user = (User) request.getSession().getAttribute(ConstantManager.SESSION_USER_PARAM_NAME);
        String typeIdS = request.getParameter("tid");

        Integer typeId = Integer.valueOf(typeIdS);
        InstitutionType institutionType = lookupInstitutionTypeFacade().find(typeId);

        if (!institutionType.getUser().equals(user) && user.getType() != org.ipo.mm.web.util.security.SecurityManager.USER_TYPE_ADMIN) {
            ////    throw new IllegalPrivilegeException("You do not have privilage to change this entity...");
        }

        request.getSession().setAttribute("updateType.type", institutionType);

        ActionForward actionForward = mapping.findForward(ConstantManager.NAVIGATION_TYPE_FORM);
        return actionForward;
    }
        public ActionForward viewTypeForm(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        User user = (User) request.getSession().getAttribute(ConstantManager.SESSION_USER_PARAM_NAME);
        String typeIdS = request.getParameter("tid");
        Integer typeId = Integer.valueOf(typeIdS);
        InstitutionType institutionType = lookupInstitutionTypeFacade().find(typeId);
        if (!institutionType.getUser().equals(user) && user.getType() != org.ipo.mm.web.util.security.SecurityManager.USER_TYPE_ADMIN) {
            ////    throw new IllegalPrivilegeException("You do not have privilage to change this entity...");
        }
        request.getSession().setAttribute("updateType.type", institutionType);
        ActionForward actionForward = mapping.findForward(ConstantManager.NAVIGATION_TYPE_FORM);
        return actionForward;
    }

    public ActionForward deleteType(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {


        String typeIdS = request.getParameter("tid");
        User user = (User) request.getSession().getAttribute(ConstantManager.SESSION_USER_PARAM_NAME);

        Integer typeId = Integer.valueOf(typeIdS);
        InstitutionType institutionType = lookupInstitutionTypeFacade().find(typeId);
        institutionType.setDeleted(true);
        lookupInstitutionTypeFacade().edit(institutionType);

        lookupLogFacade().logDelete(user, ConstantManager.TYPE_NAME, institutionType.getName());
        notifyOperatoinStatus(ConstantManager.OPERATION_TYPE_DELETE, ConstantManager.TYPE_ENTITY_NAME_RES_KEY, institutionType.getName(), request);
        BreadCrumbs bc = (BreadCrumbs) request.getSession().getAttribute(ConstantManager.SESSION_BREADCRUMB_PARAM_NAME);

        ActionForward actionForward = bc.pop().getActionForward();
        return actionForward;
    }

    public ActionForward showTypes(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        pushBreadCrumb("All institution types", request);

        List<InstitutionType> allTypes = lookupInstitutionTypeFacade().findAll();
        request.setAttribute("showTypes.types", allTypes);

        ActionForward actionForward = mapping.findForward(ConstantManager.NAVIGATION_TYPE_LIST);
        return actionForward;
    }

    public ActionForward showCreateRegionForm(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        pushBreadCrumb("Create region", request);

        ActionForward actionForward = mapping.findForward(ConstantManager.NAVIGATION_REGION_FORM);
        return actionForward;
    }

    public ActionForward showUpdateRegionForm(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        pushBreadCrumb("Update region", request);
        User user = (User) request.getSession().getAttribute(ConstantManager.SESSION_USER_PARAM_NAME);
        String regionIdS = request.getParameter("rid");
        Integer regionId = Integer.valueOf(regionIdS);
        InstitutionRegion institutionRegion = lookupInstitutionRegionFacade().find(regionId);
        request.getSession().setAttribute("updateRegion.region", institutionRegion);
        ActionForward actionForward = mapping.findForward(ConstantManager.NAVIGATION_REGION_FORM);
        return actionForward;
    }
    public ActionForward viewRegionForm(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        User user = (User) request.getSession().getAttribute(ConstantManager.SESSION_USER_PARAM_NAME);
        String regionIdS = request.getParameter("rid");
        Integer regionId = Integer.valueOf(regionIdS);
        InstitutionRegion institutionRegion = lookupInstitutionRegionFacade().find(regionId);
        request.getSession().setAttribute("updateRegion.region", institutionRegion);
        ActionForward actionForward = mapping.findForward(ConstantManager.NAVIGATION_REGION_FORM);
        return actionForward;
    }
    public ActionForward deleteRegion(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {


        User user = (User) request.getSession().getAttribute(ConstantManager.SESSION_USER_PARAM_NAME);
        String regionIdS = request.getParameter("rid");
        Integer regionId = Integer.valueOf(regionIdS);

        InstitutionRegion institutionRegion = lookupInstitutionRegionFacade().find(regionId);
        institutionRegion.setDeleted(true);
        lookupInstitutionRegionFacade().edit(institutionRegion);

        //log
        lookupLogFacade().logDelete(user, ConstantManager.REGION_NAME, institutionRegion.getName());
        notifyOperatoinStatus(ConstantManager.OPERATION_TYPE_DELETE, ConstantManager.REGION_ENTITY_NAME_RES_KEY, institutionRegion.getName(), request);

        BreadCrumbs bc = (BreadCrumbs) request.getSession().getAttribute(ConstantManager.SESSION_BREADCRUMB_PARAM_NAME);

        ActionForward actionForward = bc.pop().getActionForward();
        return actionForward;
    }

    public ActionForward showRegions(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        pushBreadCrumb("All regions", request);

        List<InstitutionRegion> allRegions = lookupInstitutionRegionFacade().findAll();
        request.setAttribute("showRegions.regions", allRegions);

        ActionForward actionForward = mapping.findForward(ConstantManager.NAVIGATION_REGION_LIST);
        return actionForward;
    }

    public ActionForward showCreateFamilyForm(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        pushBreadCrumb("Create family", request);

        ActionForward actionForward = mapping.findForward(ConstantManager.NAVIGATION_FAMILY_FORM);
        return actionForward;
    }

    public ActionForward showUpdateFamilyForm(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        pushBreadCrumb("Update family", request);
        String familyIdS = request.getParameter("fid");
        Integer familyId = Integer.valueOf(familyIdS);
        User user = (User) request.getSession().getAttribute(ConstantManager.SESSION_USER_PARAM_NAME);
        InstitutionFamily institutionFamily = lookupInstitutionFamilyFacade().find(familyId);
        request.getSession().setAttribute("updateFamily.family", institutionFamily);
        ActionForward actionForward = mapping.findForward(ConstantManager.NAVIGATION_FAMILY_FORM);
        return actionForward;
    }


    public ActionForward viewFamilyForm(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        String familyIdS = request.getParameter("fid");
        Integer familyId = Integer.valueOf(familyIdS);
        User user = (User) request.getSession().getAttribute(ConstantManager.SESSION_USER_PARAM_NAME);
        InstitutionFamily institutionFamily = lookupInstitutionFamilyFacade().find(familyId);
        request.getSession().setAttribute("updateFamily.family", institutionFamily);
        ActionForward actionForward = mapping.findForward(ConstantManager.NAVIGATION_FAMILY_FORM);
        return actionForward;
    }

    public ActionForward deleteFamily(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {


        String familyIdS = request.getParameter("fid");
        Integer familyId = Integer.valueOf(familyIdS);
        User user = (User) request.getSession().getAttribute(ConstantManager.SESSION_USER_PARAM_NAME);

        InstitutionFamily institutionFamily = lookupInstitutionFamilyFacade().find(familyId);
        institutionFamily.setDeleted(true);
        lookupInstitutionFamilyFacade().edit(institutionFamily);
        // log
        lookupLogFacade().logDelete(user, ConstantManager.FAMILY_NAME, institutionFamily.getName());

        notifyOperatoinStatus(ConstantManager.OPERATION_TYPE_DELETE, ConstantManager.FAMILY_ENTITY_NAME_RES_KEY, institutionFamily.getName(), request);
        BreadCrumbs bc = (BreadCrumbs) request.getSession().getAttribute(ConstantManager.SESSION_BREADCRUMB_PARAM_NAME);

        ActionForward actionForward = bc.pop().getActionForward();
        return actionForward;
    }

    public ActionForward showFamilies(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        pushBreadCrumb("All institution families", request);

        List<InstitutionFamily> allFamilys = lookupInstitutionFamilyFacade().findAll();
        request.setAttribute("showFamilies.families", allFamilys);

        String mailToLinkPrefix = "MAIL_TO_FAMILY_";
        for (int i = 0; i < allFamilys.size(); i++) {
            ArrayList<String> mails = new ArrayList<String>();

            InstitutionFamily family = allFamilys.get(i);
            for (Iterator<Institution> it = family.getInstitutionCollection().iterator(); it.hasNext();) {
                Institution institution = it.next();
                if (institution.getEmail().length() > 0) {
                    addMail(mails, institution.getEmail());
                }
                for (Iterator<Representative> it1 = institution.getRepresentativeCollection().iterator(); it1.hasNext();) {
                    Representative representative = it1.next();
                    if (representative.getEmail().length() > 0) {
                        addMail(mails, representative.getEmail());
                    }

                }

            }
            //ovde lista mailova treba da se nekako poveze sa familijom
            request.setAttribute(mailToLinkPrefix + family.getId(), mails);

        }


        ActionForward actionForward = mapping.findForward(ConstantManager.NAVIGATION_FAMILY_LIST);
        return actionForward;
    }

    /**
     * fill ArrayList mails with strings formated as "mailto:mail1@example.com,mail2@example.com"
     * @param mails
     * @param mail
     */
    private void addMail(ArrayList<String> mails, String mail) {
        if (mails.size() == 0) {
            String m = "mailto:";
            mails.add(m);
        }
        //get last list
        String mailList = mails.remove(mails.size() - 1);

        //check if length is too much
        if (mailList.length() + mail.length() > 2000) {
            mails.add(mailList);
            String m = "mailto:";
            mailList = m;
        }

        if (mailList.charAt(mailList.length() - 1) != ':') {
            mailList += ",";
        }
        mailList += mail;
        mails.add(mailList);

    }

    public ActionForward showCreateUserForm(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        pushBreadCrumb("Create user", request);

        ActionForward actionForward = mapping.findForward(ConstantManager.NAVIGATION_USER_FORM);
        return actionForward;
    }

    public ActionForward showUpdateUserForm(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        pushBreadCrumb("Update user", request);

        String userIdS = request.getParameter("uid");


        User user = lookupUserFacade().find(userIdS);
        request.getSession().setAttribute("updateUser.user", user);

        ActionForward actionForward = mapping.findForward(ConstantManager.NAVIGATION_USER_FORM);
        return actionForward;
    }

    public ActionForward deleteUser(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {


        String userIdS = request.getParameter("uid");

        User user = lookupUserFacade().find(userIdS);
        user.setDeleted(true);
        lookupUserFacade().edit(user);

        BreadCrumbs bc = (BreadCrumbs) request.getSession().getAttribute(ConstantManager.SESSION_BREADCRUMB_PARAM_NAME);

        ActionForward actionForward = bc.pop().getActionForward();
        return actionForward;
    }

    public ActionForward showUsers(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        pushBreadCrumb("All users", request);

        List<User> allUsers = lookupUserFacade().findAll();
        request.setAttribute("showUsers.users", allUsers);

        ActionForward actionForward = mapping.findForward(ConstantManager.NAVIGATION_USER_LIST);
        return actionForward;
    }

    public ActionForward showCreateInstForm(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        pushBreadCrumb(ConstantManager.BC_INST_CREATE, request);

        ActionForward actionForward = null;
        //load all inst. regions and store it in session
        List<InstitutionRegion> regions = lookupInstitutionRegionFacade().findAll();
        request.getSession().setAttribute("dispatch.showCreatInstForm.regions", regions);
        //load all inst. families and store it in session
        List<InstitutionFamily> families = lookupInstitutionFamilyFacade().findAll();
        request.getSession().setAttribute("dispatch.showCreatInstForm.families", families);
        //load all inst. types and store it in session
        List<InstitutionType> types = lookupInstitutionTypeFacade().findAll();
        request.getSession().setAttribute("dispatch.showCreatInstForm.types", types);
        //load all inst. types and store it in session
        List<City> cities = lookupCityFacade().findAll();
        request.getSession().setAttribute("dispatch.showCreatInstForm.cities", cities);

        // request.getSession().setAttribute(ConstantManager.SESSION_INST_RESET_FORM, new Boolean(true));
        List<Institution> allInst = lookupInstitutionFacade().findAll();
        request.setAttribute("allInst", allInst);

        InstitutionBean iBean = (InstitutionBean) request.getSession().getAttribute("InstitutionBean");
        if (iBean != null) {
            iBean.reset(mapping, request);
        }

        actionForward = mapping.findForward(ConstantManager.NAVIGATION_INSTITUTION_FORM);


        return actionForward;
    }

    public ActionForward showInstitutions(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        pushBreadCrumb(ConstantManager.BC_INST_LIST, request);

        List<Institution> insts = lookupInstitutionFacade().findAll();
        request.setAttribute("dispatcher.showInstitutionList.insts", insts);

        ActionForward actionForward = mapping.findForward(ConstantManager.NAVIGATION_INSTITUTION_LIST);
        return actionForward;
    }

    public ActionForward showUpdateInstForm(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        ActionForward actionForward = null;
        User user = (User) request.getSession().getAttribute(ConstantManager.SESSION_USER_PARAM_NAME);
        pushBreadCrumb(ConstantManager.BC_INST_UPDATE, request);
        //load all inst. regions and store it in session
        List<InstitutionRegion> regions = lookupInstitutionRegionFacade().findAll();
        request.setAttribute("dispatch.showCreatInstForm.regions", regions);
        //load all inst. families and store it in session
        List<InstitutionFamily> families = lookupInstitutionFamilyFacade().findAll();
        request.setAttribute("dispatch.showCreatInstForm.families", families);
        //load all inst. types and store it in session
        List<InstitutionType> types = lookupInstitutionTypeFacade().findAll();
        request.setAttribute("dispatch.showCreatInstForm.types", types);
        //load all inst. types and store it in session
        List<City> cities = lookupCityFacade().findAll();
        request.setAttribute("dispatch.showCreatInstForm.cities", cities);
        //retreive inst forma database and store it in session
        String instID = request.getParameter("iid");
        Institution institution = lookupInstitutionFacade().find(Integer.valueOf(instID));
        //request.getSession().setAttribute("dispatcher.showUpdateInstForm.inst", institution);
        request.getSession().setAttribute("dispatcher_showUpdateInstForm_inst", institution);
        InstitutionBean iBean = (InstitutionBean) request.getSession().getAttribute("InstitutionBean");
        if (iBean != null) {
            iBean.reset(mapping, request);
        }
        actionForward = mapping.findForward(ConstantManager.NAVIGATION_INSTITUTION_FORM);
        return actionForward;
    }
    public ActionForward viewInstForm(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        ActionForward actionForward = null;
       // User user = (User) request.getSession().getAttribute(ConstantManager.SESSION_USER_PARAM_NAME);
        //load all inst. regions and store it in session
        String instID = request.getParameter("iid");
        Institution institution = lookupInstitutionFacade().find(Integer.valueOf(instID));
        List<InstitutionRegion> regions =Arrays.asList(institution.getRegion());
        request.setAttribute("dispatch.showCreatInstForm.regions", regions);
        //load all inst. families and store it in session
        List<InstitutionFamily> families = Arrays.asList(institution.getFamily());
        request.setAttribute("dispatch.showCreatInstForm.families", families);
        //load all inst. types and store it in session
        List<InstitutionType> types = Arrays.asList(institution.getType());
        request.setAttribute("dispatch.showCreatInstForm.types", types);
        //load all inst. types and store it in session
        List<City> cities = Arrays.asList(institution.getCity());
        request.setAttribute("dispatch.showCreatInstForm.cities", cities);
        //retreive inst forma database and store it in session
        //request.getSession().setAttribute("dispatcher.showUpdateInstForm.inst", institution);
        request.getSession().setAttribute("dispatcher_showUpdateInstForm_inst", institution);
        InstitutionBean iBean = (InstitutionBean) request.getSession().getAttribute("InstitutionBean");
        if (iBean != null) {
            iBean.reset(mapping, request);
        }
        actionForward = mapping.findForward(ConstantManager.NAVIGATION_INSTITUTION_FORM);
        return actionForward;
    }

    public ActionForward deleteInstitution(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {


        String instIDString = request.getParameter("iid");
        User user = (User) request.getSession().getAttribute(ConstantManager.SESSION_USER_PARAM_NAME);
        Integer instID = Integer.valueOf(instIDString);

        //lookup for facades
        MeetingFacadeLocal meetingFacadeLocal = lookupMeetingFacade();
        RepresentativeFacadeLocal representativeFacadeLocal = lookupRepresentativeFacade();
        InstitutionFacadeLocal institutionFacadeLocal = lookupInstitutionFacade();

        //load institution from database by id
        Institution institution = institutionFacadeLocal.find(instID);


        //deleteing representatives & meetings connected to this institution
        Collection<Representative> representatives = institution.getRepresentativeCollection();

        for (Representative representative : representatives) {

            //delete all meeting to which this representaive attended nad organized
//            Collection<Meeting> meetingsAttended = representative.getMeetingCollection();
//            for (Meeting meeting : meetingsAttended) {
//                meeting.setDeleted(true);
//                meetingFacadeLocal.edit(meeting);
//            }
//
//            Collection<Meeting> meetingsOrganized = representative.getMeetingCollection1();
//            for (Meeting meeting : meetingsOrganized) {
//                meeting.setDeleted(true);
//                meetingFacadeLocal.edit(meeting);
//            }

            //delete representative
            representative.setDeleted(true);
            representativeFacadeLocal.edit(representative);
        }

        institution.setDeleted(true);
        institutionFacadeLocal.edit(institution);

        //log
        lookupLogFacade().logDelete(user, ConstantManager.INSTITUTION_NAME, institution.getName());

        notifyOperatoinStatus(ConstantManager.OPERATION_TYPE_DELETE, ConstantManager.INSTITUTION_ENTITY_NAME_RES_KEY, institution.getName(), request);
        BreadCrumbs bc = (BreadCrumbs) request.getSession().getAttribute(ConstantManager.SESSION_BREADCRUMB_PARAM_NAME);

        ActionForward actionForward = bc.pop().getActionForward();
        return actionForward;
    }

    public ActionForward showCreateReprForm(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        ActionForward forward = null;
        pushBreadCrumb(ConstantManager.BC_REPR_CREATE, request);
        //load all institutions from db
        List<Institution> institutions = lookupInstitutionFacade().findAll();
        request.getSession().setAttribute("dispatcher.showCreateReprForm.insts", institutions);

        //load all inst. types and store it in session
        List<City> cities = lookupCityFacade().findAll();
        request.getSession().setAttribute("dispatch.showCreateReprForm.cities", cities);
        //load reprs and inst for intelisense
        List<Representative> allReps = lookupRepresentativeFacade().findAll();
        request.setAttribute("allReps", allReps);
        List<Institution> allInst = lookupInstitutionFacade().findAll();
        request.setAttribute("allInst", allInst);

        RepresentativeBean rBean = (RepresentativeBean) request.getSession().getAttribute("RepresentativeBean");
        if (rBean != null) {
            rBean.reset(mapping, request);
        }


        forward = mapping.findForward(ConstantManager.NAVIGATION_REPRESENTATIVE_FORM);

        return forward;

    }

    public ActionForward showReprs(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        pushBreadCrumb(ConstantManager.BC_REPR_LIST, request);
        List<Representative> allReps = lookupRepresentativeFacade().findAll();
        request.setAttribute("allReps", allReps);
        List<Institution> allInst = lookupInstitutionFacade().findAll();
        request.setAttribute("allInst", allInst);
        //List<Representative> reprs = lookupRepresentativeFacade().findAll();
        //request.setAttribute("dispatcher.showReprList.reprs", reprs);

        ActionForward actionForward = mapping.findForward(ConstantManager.NAVIGATION_REPRESENTATIVE_LIST);
        return actionForward;
    }

    public ActionForward deleteRepresentative(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {


        String reprIDString = request.getParameter("rid");
        User user = (User) request.getSession().getAttribute(ConstantManager.SESSION_USER_PARAM_NAME);

        int reprId = Integer.parseInt(reprIDString);
        RepresentativeFacadeLocal representativeFacadeLocal = lookupRepresentativeFacade();

        representativeFacadeLocal.markAsDeleted(reprId);

        Representative representative = representativeFacadeLocal.find(reprId);
        lookupLogFacade().logDelete(user, ConstantManager.REPRESENTATIVE_NAME, representative.getFirstName() + " " + representative.getLastName());
        notifyOperatoinStatus(ConstantManager.OPERATION_TYPE_DELETE, ConstantManager.REPRESENTATIVE_ENTITY_NAME_RES_KEY, representative.getFirstName() + " " + representative.getLastName(), request);

        BreadCrumbs bc = (BreadCrumbs) request.getSession().getAttribute(ConstantManager.SESSION_BREADCRUMB_PARAM_NAME);

        ActionForward actionForward = bc.pop().getActionForward();


        return actionForward;

    }

    public ActionForward showUpdateReprForm(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        List<Representative> allReps = lookupRepresentativeFacade().findAll();
        request.setAttribute("allReps", allReps);
        List<Institution> allInst = lookupInstitutionFacade().findAll();
        request.setAttribute("allInst", allInst);
        ActionForward actionForward = null;
        pushBreadCrumb(ConstantManager.BC_REPR_UPDATE, request);
        String reprIDString = request.getParameter("rid");
        User user = (User) request.getSession().getAttribute(ConstantManager.SESSION_USER_PARAM_NAME);
        int reprId = Integer.parseInt(reprIDString);
        Representative repr = lookupRepresentativeFacade().find(reprId);
        request.getSession().setAttribute(ConstantManager.SESSION_REPRESENTATIVE_FOR_UPDATE_PN, repr);
        //load all institutions from db
        List<Institution> institutions = lookupInstitutionFacade().findAll();
        request.getSession().setAttribute("dispatcher.showCreateReprForm.insts", institutions);
        RepresentativeBean rBean = (RepresentativeBean) request.getSession().getAttribute("RepresentativeBean");
        if (rBean != null) {
            rBean.reset(mapping, request);
        }
        actionForward = mapping.findForward(ConstantManager.NAVIGATION_REPRESENTATIVE_FORM);
        return actionForward;
    }


    public ActionForward viewReprForm(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        //List<Representative> allReps = lookupRepresentativeFacade().findAll();
        //request.setAttribute("allReps", allReps);
        //List<Institution> allInst = lookupInstitutionFacade().findAll();
        //request.setAttribute("allInst", allInst);
        ActionForward actionForward = null;
        String reprIDString = request.getParameter("rid");
        User user = (User) request.getSession().getAttribute(ConstantManager.SESSION_USER_PARAM_NAME);
        int reprId = Integer.parseInt(reprIDString);
        Representative repr = lookupRepresentativeFacade().find(reprId);
        request.getSession().setAttribute(ConstantManager.SESSION_REPRESENTATIVE_FOR_UPDATE_PN, repr);
        //load all institutions from db
        List<Institution> institutions = Arrays.asList(repr.getInstitution());
        request.setAttribute("dispatcher.showCreateReprForm.insts", institutions);
        RepresentativeBean rBean = (RepresentativeBean) request.getSession().getAttribute("RepresentativeBean");
        if (rBean != null) {
            rBean.reset(mapping, request);
        }
        actionForward = mapping.findForward(ConstantManager.NAVIGATION_REPRESENTATIVE_FORM);
        return actionForward;
    }

    public ActionForward showCreateMeetingForm(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        ActionForward forward = null;
        List<Representative> reprs = lookupRepresentativeFacade().findAll();
        request.getSession().setAttribute("allReprs", reprs);
        String flagParamName = "rm";
               //ActionErrors errors = super.validate(mapping, request);
        MessageResources mResources = (MessageResources) request.getAttribute(Globals.MESSAGES_KEY);
        String createMessage = mResources.getMessage(getLocale(request), "meetings_createnew");
        pushBreadCrumb(createMessage, request);

        //pushBreadCrumb(ConstantManager.BC_MEETING_CREATE, request);


        Object createMeetingFromSessionFlag = request.getSession().getAttribute(ConstantManager.SESSION_LOCK_MEETING);
        String createMeetingFromUrlParamFlag = request.getParameter(flagParamName);

        // check for it might be return to the page from creating new representative
        if (createMeetingFromUrlParamFlag != null && createMeetingFromSessionFlag == null) {
            Meeting meeting = new Meeting();


            meeting.setRepresentativeCollection(new ArrayList<Representative>());
            meeting.setMeetingActions(new ArrayList<Actions>());
            request.getSession().setAttribute(ConstantManager.SESSION_MEETING_PROCESS_AN, meeting);
        }

        request.getSession().removeAttribute(ConstantManager.SESSION_LOCK_MEETING);


        request.getSession().setAttribute("updateMeetingPath", request.getRequestURL().toString() + "?" + request.getQueryString());

        MeetingBean mBean = (MeetingBean) request.getSession().getAttribute("MeetingBean");
        //List<Representative> results = lookupRepresentativeFacade().search(searchQuery);
        if (mBean != null) {
            mBean.reset(mapping, request);
        }

        forward = mapping.findForward(ConstantManager.NAVIGATION_MEETING_FORM);
        return forward;
    }

    public ActionForward showMeetings(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        pushBreadCrumb(ConstantManager.BC_MEETING_LIST, request);

        List<Meeting> meetings = lookupMeetingFacade().findAll();
        request.setAttribute("dispatcher.showMeetingList.meetings", meetings);

        ActionForward actionForward = mapping.findForward(ConstantManager.NAVIGATION_MEETING_LIST);
        return actionForward;
    }

    public ActionForward deleteMeeting(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {


        String reprIDString = request.getParameter("mid");
        User user = (User) request.getSession().getAttribute(ConstantManager.SESSION_USER_PARAM_NAME);

        int meetingId = Integer.parseInt(reprIDString);
        lookupMeetingFacade().markDeleted(meetingId);

        // log
        Meeting meeting = lookupMeetingFacade().find(meetingId);
        lookupLogFacade().logDelete(user, ConstantManager.MEETING_NAME, meeting.getEventName());
        notifyOperatoinStatus(ConstantManager.OPERATION_TYPE_DELETE, ConstantManager.MEETING_ENTITY_NAME_RES_KEY, meeting.getEventName(), request);

        BreadCrumbs bc = (BreadCrumbs) request.getSession().getAttribute(ConstantManager.SESSION_BREADCRUMB_PARAM_NAME);

        ActionForward actionForward = bc.pop().getActionForward();


        return actionForward;

    }

    public ActionForward showUpdateMeetingForm(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        ActionForward actionForward = null;
        pushBreadCrumb(ConstantManager.BC_MEETING_UPDATE, request);
        User user = (User) request.getSession().getAttribute(ConstantManager.SESSION_USER_PARAM_NAME);
        Object resetMeeting = request.getSession().getAttribute(ConstantManager.SESSION_LOCK_MEETING);
        if (resetMeeting == null) {
            request.getSession().setAttribute("updateMeetingPath", request.getRequestURL().toString() + "?" + request.getQueryString());
            String meetingId = request.getParameter("mid");
            Meeting meeting = lookupMeetingFacade().findFetchDocs(Integer.parseInt(meetingId));
            List<Document> documentsOfMeeting = lookupDocumentFacade().findByMeeting(meeting);
            meeting.setDocumentCollection(documentsOfMeeting);
            request.getSession().setAttribute(ConstantManager.SESSION_MEETING_PROCESS_AN, meeting);
        }
        request.getSession().removeAttribute(ConstantManager.SESSION_LOCK_MEETING);
        request.getSession().setAttribute("updateMeetingPath", request.getRequestURL().toString() + "?" + request.getQueryString());
        MeetingBean mBean = (MeetingBean) request.getSession().getAttribute("MeetingBean");
        if (mBean != null) {
            mBean.reset(mapping, request);
        }
        actionForward = mapping.findForward(ConstantManager.NAVIGATION_MEETING_FORM);
        return actionForward;
    }

    public ActionForward showDisplayMeetingForm(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        ActionForward actionForward = null;
        pushBreadCrumb(ConstantManager.BC_MEETING_UPDATE, request);
        User user = (User) request.getSession().getAttribute(ConstantManager.SESSION_USER_PARAM_NAME);
        Object resetMeeting = request.getSession().getAttribute(ConstantManager.SESSION_LOCK_MEETING);
        if (resetMeeting == null) {
            String meetingId = request.getParameter("mid");
            Meeting meeting = lookupMeetingFacade().findFetchDocs(Integer.parseInt(meetingId));
            request.getSession().setAttribute(ConstantManager.SESSION_MEETING_PROCESS_AN, meeting);
        }
        request.getSession().removeAttribute(ConstantManager.SESSION_LOCK_MEETING);
        MeetingBean mBean = (MeetingBean) request.getSession().getAttribute("MeetingBean");
        if (mBean != null) {
            mBean.reset(mapping, request);
        }
        actionForward = mapping.findForward(ConstantManager.NAVIGATION_MEETING_FORM);
        return actionForward;
    }


    public ActionForward viewMeetingForm(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        ActionForward actionForward = null;
        pushBreadCrumb(ConstantManager.BC_MEETING_UPDATE, request);
        User user = (User) request.getSession().getAttribute(ConstantManager.SESSION_USER_PARAM_NAME);
        Object resetMeeting = request.getSession().getAttribute(ConstantManager.SESSION_LOCK_MEETING);
        if (resetMeeting == null) {
            request.getSession().setAttribute("updateMeetingPath", request.getRequestURL().toString() + "?" + request.getQueryString());
            String meetingId = request.getParameter("mid");
            Meeting meeting = lookupMeetingFacade().findFetchDocs(Integer.parseInt(meetingId));
            List<Document> documentsOfMeeting = lookupDocumentFacade().findByMeeting(meeting);
            meeting.setDocumentCollection(documentsOfMeeting);
            request.getSession().setAttribute(ConstantManager.SESSION_MEETING_PROCESS_AN, meeting);
        }
        request.getSession().removeAttribute(ConstantManager.SESSION_LOCK_MEETING);
        request.getSession().setAttribute("updateMeetingPath", request.getRequestURL().toString() + "?" + request.getQueryString());
        MeetingBean mBean = (MeetingBean) request.getSession().getAttribute("MeetingBean");
        if (mBean != null) {
            mBean.reset(mapping, request);
        }
        actionForward = mapping.findForward(ConstantManager.NAVIGATION_MEETING_FORM);
        return actionForward;
    }

    public ActionForward showUpdateActionsForm(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) {

        ActionForward actionForward = null;
        Actions actions = null;
        String actionId = (String) request.getParameter("aid");

        Meeting meeting = (Meeting) request.getSession().getAttribute(ConstantManager.SESSION_MEETING_PROCESS_AN);
        if (meeting != null) {
            Collection<Actions> actionsCollection = meeting.getMeetingActions();

            Iterator<Actions> iterator = actionsCollection.iterator();
            while (iterator.hasNext()) {
                Actions some = iterator.next();
                if (some.getId().equals(Integer.parseInt(actionId))) {
                    actions = some;
                }
            }
        }
        if (actions == null) {
            actions = lookupActionsFacade().find(Integer.parseInt(actionId));
        }





        request.getSession().setAttribute(ConstantManager.SESSION_ACTIONS_PROCESS, actions);
        request.getSession().setAttribute(ConstantManager.SESSION_LOCK_MEETING, new Object());
        actionForward = mapping.findForward(ConstantManager.NAVIGATION_ACTIONS_FORM);

        return actionForward;
    }

    public ActionForward showCreateActionsForm(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) {

        ActionForward actionForward = null;

        request.getSession().setAttribute(ConstantManager.SESSION_LOCK_MEETING, new Object());

        actionForward = mapping.findForward(ConstantManager.NAVIGATION_ACTIONS_FORM);

        return actionForward;

    }

    public ActionForward deleteActions(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) {


        String ACTION_ID_PARAM_NAME = "aid";
        String actionId = request.getParameter(ACTION_ID_PARAM_NAME);

        Meeting meeting = (Meeting) request.getSession().getAttribute(ConstantManager.SESSION_MEETING_PROCESS_AN);
        if (meeting != null) {
            Actions aToRemove = new Actions(Integer.parseInt(actionId));
            meeting.getMeetingActions().remove(aToRemove);
            lookupMeetingFacade().edit(meeting);
        }

        Actions actions = lookupActionsFacade().find(Integer.parseInt(actionId));
        if (actions != null) {
            lookupActionsFacade().remove(actions);
        }



        BreadCrumbs breadCrumbs = (BreadCrumbs) request.getSession().getAttribute(ConstantManager.SESSION_BREADCRUMB_PARAM_NAME);

        return breadCrumbs.pop().getActionForward();


    }

    public ActionForward showCloseWindowPage(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) {

        ActionForward actionForward = null;
        actionForward = mapping.findForward(ConstantManager.NAVIGATION_CLOSE_WINDOW);
        return actionForward;
    }

    private ActionsFacadeLocal lookupActionsFacade() {
        try {
            Context c = new InitialContext();
            return (ActionsFacadeLocal) c.lookup("java:comp/env/ActionsFacade");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

    private CityFacadeLocal lookupCityFacade() {
        try {
            Context c = new InitialContext();
            return (CityFacadeLocal) c.lookup("java:comp/env/CityFacade");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

    /*
     * Pushs new element to user navigation stack
     *
     * @param name desc of the page and id for new stack element
     */
    private void pushBreadCrumb(String name, HttpServletRequest request) {

        BreadCrumbs bc = (BreadCrumbs) request.getSession().getAttribute(ConstantManager.SESSION_BREADCRUMB_PARAM_NAME);
        bc.push(name, request);

        //        String clearStack = request.getParameter("clearStack");
//        BreadCrumbs bc = (BreadCrumbs) request.getSession().getAttribute(ConstantManager.SESSION_BREADCRUMB_PARAM_NAME);
//        if (clearStack != null) {
//            bc.clearStack();
//        }
//        String url = request.getRequestURI() + "?" + request.getQueryString();
//        url = url.substring(url.indexOf("/", url.indexOf("/") + 1));
//        ActionForward f = new ActionForward(url, false);
//
//        bc.push(name, f);
//        request.setAttribute("title", name);
    }

    private InstitutionFacadeLocal lookupInstitutionFacade() {
        try {
            Context c = new InitialContext();
            return (InstitutionFacadeLocal) c.lookup("java:comp/env/InstitutionFacade");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

    private InstitutionTypeFacadeLocal lookupInstitutionTypeFacade() {
        try {
            Context c = new InitialContext();
            return (InstitutionTypeFacadeLocal) c.lookup("java:comp/env/InstitutionTypeFacade");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

    private InstitutionRegionFacadeLocal lookupInstitutionRegionFacade() {
        try {
            Context c = new InitialContext();
            return (InstitutionRegionFacadeLocal) c.lookup("java:comp/env/InstitutionRegionFacade");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

    private InstitutionFamilyFacadeLocal lookupInstitutionFamilyFacade() {
        try {
            Context c = new InitialContext();
            return (InstitutionFamilyFacadeLocal) c.lookup("java:comp/env/InstitutionFamilyFacade");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

    private MeetingFacadeLocal lookupMeetingFacade() {
        try {
            Context c = new InitialContext();
            return (MeetingFacadeLocal) c.lookup("java:comp/env/MeetingFacade");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

    private RepresentativeFacadeLocal lookupRepresentativeFacade() {
        try {
            Context c = new InitialContext();
            return (RepresentativeFacadeLocal) c.lookup("java:comp/env/RepresentativeFacade");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

    private UserFacadeLocal lookupUserFacade() {
        try {
            Context c = new InitialContext();
            return (UserFacadeLocal) c.lookup("java:comp/env/UserFacade");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

    private LogFacadeLocal lookupLogFacade() {
        try {
            Context c = new InitialContext();
            return (LogFacadeLocal) c.lookup("java:comp/env/LogFacade");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

    private DocumentFacadeLocal lookupDocumentFacade() {
        try {
            Context c = new InitialContext();
            return (DocumentFacadeLocal) c.lookup("java:comp/env/DocumentFacade");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

    private void notifyOperatoinStatus(String operationMessageKey, String entityNameKey, String entityName, HttpServletRequest request) {

        MessageResources mResources = getResources(request);
        String typeEntityName = mResources.getMessage(getLocale(request), entityNameKey);
//TODO change name of variable
        ActionMessages messages = new ActionMessages();

        Object[] l = new Object[2];
        l[0] = typeEntityName;
        l[1] = entityName;
        ActionMessage actionMessage1 = new ActionMessage(operationMessageKey, l);
        ActionMessage actionMessage = new ActionMessage(operationMessageKey, typeEntityName);

        messages.add("operation_status", actionMessage1);
        saveMessages(request, messages);

    }
}
